<template>
    <div class="flex-row mb10 rule-item-wrap" v-for="(item, index) in ruleList" :key="index">
        <span class="title" v-if="index === 0">{{ props.title }}</span>
        <el-select
            v-model="item.connect"
            v-else
            class="select"
            placeholder="Select"
            size="small"
            @change="updateVal"
        >
            <el-option label="或" value="or" />
            <el-option label="且" value="and" />
        </el-select>
        <el-select
            v-model="item.type"
            class="m-2"
            placeholder="Select"
            size="small"
            @change="updateVal"
            style="width: 100px;"
        >
            <el-option label="包含" :value="true" />
            <el-option label="不包含" :value="false" />
        </el-select>
        <el-input
            v-model="item.keyword"
            placeholder="请输入"
            @change="updateVal"
            size="small"
            style="width: 214px;"
        />
        <div class="btn-wrap">
            <el-button @click="addRuleItem" class="border plus-btn" size="small" v-if="index === 0">
            <i class="iconfont icon-plus" />
            </el-button>
            <el-button @click="delRuleItem(item)" class="border minus-btn"  size="small" v-if="index !== 0">
            <i class="iconfont icon-minus" />
            </el-button>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';

// 定义父组件传过来的值
const props = defineProps({
	title : {
		type: String,
		default: () => '',
	},
    modelValue: {
      type: Array,
      default: () => [],
    },
});

const emit = defineEmits(['update:modelValue']);

const ruleList = ref([{
    type: true,
    keyword: '',
    connect: 'and'
}]);

// 标记本地更新，防止循环
const localUpdate = ref(false);

const updateVal = () => {
    localUpdate.value = true;
    emit('update:modelValue', ruleList.value);
};

const addRuleItem = () => {
    ruleList.value.push({
        type: true,
        keyword: '',
        connect: 'and'
    });
    updateVal();
}

const delRuleItem = (rule: any) => {
    ruleList.value = ruleList.value.filter((item: any) => item !== rule);
    updateVal();
};

onMounted(() => {
    if (props.modelValue && props.modelValue.length) {
        ruleList.value  = [...props.modelValue];
    }
});

// 监听 modelValue，外部变更时同步 ruleList，防止循环
watch(() => props.modelValue, (newVal) => {
    if (localUpdate.value) {
        localUpdate.value = false;
        return;
    }
    if (Array.isArray(newVal)) {
        ruleList.value = [...newVal];
    }
}, { deep: true });
</script>
<style lang="scss" scoped>
.title {
    width: 80px;
}

.select {
    width: 80px;
}
</style>